package com.cjj.thread_tongxun;

/**
 * 共享资源对象
 */
class Res {
    public String name;
    public String sex;
    public boolean flag = false;
}

/**
 * 写入线程
 */
class InputThread extends Thread {

    public Res res;

    public InputThread(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            synchronized (res) {
                if (res.flag) {
                    try {
                        // wait可以让当前线程从运行状态变成休眠状态
                        res.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (count == 0) {
                    res.name = "ccc-ju";
                    res.sex = "男";
                } else {
                    res.name = "xiaofang";
                    res.sex = "女";
                }
                count = (count + 1) % 2;
                res.flag = true;
                res.notify();
            }
        }
    }
}

/**
 * 读线程
 */
class OutputThread extends Thread {
    public Res res;

    public OutputThread(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (res) {
                if(!res.flag){
                    try {
                        res.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(res.name + "----" + res.sex);
                res.flag = false;
                res.notify();
            }
        }
    }
}

/**
 * 第一个线程(input)用户，另一个线程读取(out)用户，实现写一个读一个操作
 *
 * @ClassName Thread_01
 * @Date 2021/07/17 15:48:49
 * @Created by ccc-j
 * @email ccc-ju@outlook.com
 */
public class Thread_01 {

    public static void main(String[] args) {
        Res res = new Res();
        InputThread inputThread = new InputThread(res);
        OutputThread outputThread = new OutputThread(res);
        inputThread.start();
        outputThread.start();
    }

}
